package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import model.IniUtil;
import model.exception.SVGException;
import apps.AppReg;

public class OpenListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent arg0) {

	// Get last path
	String lastPath = IniUtil.getProperty("LastPath");

	// Construct file dialog
	JFileChooser fc = new JFileChooser(lastPath);

	// Set filters
	fc.addChoosableFileFilter(new SVGFilter());
	fc.setAcceptAllFileFilterUsed(false);

	int returnVal = fc.showOpenDialog(AppReg.getFrame());

	// If chose a file
	if (returnVal == JFileChooser.APPROVE_OPTION) {
	    File file = fc.getSelectedFile();

	    AppReg.getFrame().getSVGPanel().setZoomScale(1);
	    AppReg.getFrame().getToolBar().setZoom(100);
	    // Load it into model

	    try {
		AppReg.getModel().LoadFile(file.getAbsolutePath());

	    } catch (SVGException e) {
		JOptionPane.showMessageDialog(AppReg.getFrame(),
			"SVG Exception", e.getMessage(), JOptionPane.ERROR);
		System.out.println(e.getMessage());
	    }

	    // Save to INI file
	    IniUtil.setProperty("LastPath", file.getParentFile().toString());
	}
    }
}
